package com.company.config;

import java.sql.*;

public class DbConfig {

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/select_sys?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8";
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "root";

    /**
     * 注册驱动，获取连接
     *
     * @return Connection
     * @throws Exception e
     */
    public static Connection getConn(){

        Connection conn =null;
        try{
            //注册驱动
            Class.forName(JDBC_DRIVER);
            //获取连接
            conn= DriverManager.getConnection(DB_URL, USER, PASS);
            //返回连接对象Connection
        }catch (SQLException | ClassNotFoundException e){
            e.printStackTrace();
        }

        return conn;
    }

    /**
     * 关闭资源
     *
     * @param conn Connection
     * @param stat Connection
     * @param rs   Connection
     */
    public static void close(Connection conn, Statement stat, ResultSet rs) {
        try {
            //判断有值时关闭
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stat != null) {
                stat.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
